package org.jeecg.modules.mes.produce.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.api.client.util.Lists;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataDevicearchive;
import org.jeecg.modules.mes.client.SystemClient;
import org.jeecg.modules.mes.produce.entity.MesMaintenanceRecordItem;
import org.jeecg.modules.mes.produce.entity.MesMaintenanceRecordMain;
import org.jeecg.modules.mes.produce.mapper.MesMaintenanceRecordItemMapper;
import org.jeecg.modules.mes.produce.mapper.MesMaintenanceRecordMainMapper;
import org.jeecg.modules.mes.produce.service.IMesMaintenanceRecordMainService;
import org.jeecg.modules.mes.produce.vo.MaintenanceRecordProjectVo;
import org.jeecg.modules.mes.produce.vo.OperationRecordVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.epms.util.ObjectHelper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Description: 维护保养点检记录主表
 * @Author: jeecg-boot
 * @Date: 2021-06-10
 * @Version: V1.0
 */
@Service
public class MesMaintenanceRecordMainServiceImpl extends ServiceImpl<MesMaintenanceRecordMainMapper, MesMaintenanceRecordMain> implements IMesMaintenanceRecordMainService {

    @Autowired
    private MesMaintenanceRecordItemServiceImpl mesMaintenanceRecordItemService;

    @Autowired
    private MesMaintenanceRecordMainMapper mesMaintenanceRecordMainMapper;

    @Autowired
    private MesMaintenanceRecordItemMapper mesMaintenanceRecordItemMapper;

    @Autowired
    private SystemClient systemClient;

    @Override
    public Result<?> addMesMaintenanceRecordMain(MesMaintenanceRecordMain mesMaintenanceRecordMain) {
        QueryWrapper<MesMaintenanceRecordMain> queryWrapper = new QueryWrapper();
        queryWrapper.eq("table_type_code", mesMaintenanceRecordMain.getTableTypeCode());
        queryWrapper.eq("table_name_code", mesMaintenanceRecordMain.getTableNameCode());
        queryWrapper.eq("inspection_date", mesMaintenanceRecordMain.getInspectionDate());
        if (ObjectHelper.isNotEmpty(mesMaintenanceRecordMainMapper.selectList(queryWrapper))) {
            return Result.error("该月的记录以存在，请检查！");
        }
        mesMaintenanceRecordMainMapper.insert(mesMaintenanceRecordMain);
        return Result.ok("添加成功！");
    }

    @Override
    public Result<?> queryProjectModeByCode(String tableNameCode) {
        List<String> list = Lists.newArrayList();
        list.add("开线前必须确认项目");
        if ("printing_operation_record".equals(tableNameCode)) {//印刷机作业记录表
            list.add("手动清洁钢板项目");
            list.add("钢板清洗后必须确认项目");
        }
        if ("reflow_operation_record".equals(tableNameCode)) {//回焊炉作业记录表
            list.add("生产过程必须确认项目");
        }
        return Result.ok(list);
    }

    @Override
    public Result<?> queryProjectModeByCodeAndProject(String tableNameCode, String project) {
        List<String> list = Lists.newArrayList();
        if ("printing_operation_record".equals(tableNameCode)) {//印刷机作业记录表
            if ("开线前必须确认项目".equals(project)) {
                list.add("生产机型");
                list.add("程式名称");
                list.add("PCB版本");
                list.add("钢板出厂编号");
                list.add("刮刀型号是否与SOP相符");
                list.add("锡膏型号是否与SOP相符");
                list.add("印刷参数设置是否与SOP相符");
            }
            if ("手动清洁钢板项目".equals(project)) {
                list.add("手动清洁钢板记录");
            }
            if ("钢板清洗后必须确认项目".equals(project)) {//钢板清洗后必须确认项目
                list.add("印刷治具(钢板, Support, 刮刀等)是否清洁干净");
                list.add("钢板清洁后孔壁是否有锡粉残留");
                list.add("PCB夹边是否有磨损");
                list.add("擦拭系统是否有喷溶剂,并确认溶剂量是否均匀");
            }
        }
        if ("reflow_operation_record".equals(tableNameCode)) {//回焊炉作业记录表
            if ("开线前必须确认项目".equals(project)) {
                list.add("生产机型");
                list.add("程式名称");
                list.add("标准设定值(SV)是否与SOP相符");
                list.add("轨道宽度及与前后Conveyer连接是否顺畅");
            }
            if ("生产过程必须确认项目".equals(project)) {
                list.add("标准设定值(SV)");
                list.add("实际观察值(PV)");
            }
        }
        return Result.ok(list);
    }

    @Override
    public Result<?> addMesMaintenanceRecordItemForApp(OperationRecordVo operationRecordVo) throws ParseException {
        if (ObjectHelper.isEmpty(operationRecordVo.getProjectVoList())) {
            Result.error("获取检查项目失败，请检查传入参数都否正确！");
        }
        if (ObjectHelper.isEmpty(operationRecordVo.getTableNameCode())) {
            Result.error("获取表名称编码失败，请检查传入参数都否正确！");
        }
        if (ObjectHelper.isEmpty(operationRecordVo.getProjectType())) {
            Result.error("获取项目类型失败，请检查传入参数都否正确！");
        }
        if (ObjectHelper.isEmpty(operationRecordVo.getAssignmentDate())) {
            Result.error("获取作业日期失败，请检查传入参数都否正确！");
        }
        if (ObjectHelper.isEmpty(operationRecordVo.getDayOrNight())) {
            Result.error("获取白班夜班失败，请检查传入参数都否正确！");
        }

        if (ObjectHelper.isEmpty(operationRecordVo.getAssignmentDate())) {
            operationRecordVo.setAssignmentDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        }
        MesMaintenanceRecordMain mesMaintenanceRecordMain = this.checkMaintenanceRecordMain(operationRecordVo.getTableNameCode(), operationRecordVo.getAssignmentDate());

        if (ObjectHelper.isEmpty(mesMaintenanceRecordMain)) {//没有主表数据进行添加操作
            mesMaintenanceRecordMain = this.addMaintenanceRecordMain(operationRecordVo);
        } else {
            if ("reflow_operation_record".equals(operationRecordVo.getTableNameCode())) {//回焊炉作业记录表
                mesMaintenanceRecordMain.setQuery1(operationRecordVo.getMaintainer());//工程师
            }
            mesMaintenanceRecordMain.setReviewer(operationRecordVo.getReviewer());//生产主管
            mesMaintenanceRecordMainMapper.updateById(mesMaintenanceRecordMain);
        }

        if (ObjectHelper.isEmpty(mesMaintenanceRecordMain)) {
            Result.error("添加主表信息时未找到对应的设备，请检查设备SN是否正确！");
        }

        //验证是否有重复记录
        QueryWrapper<MesMaintenanceRecordItem> queryWrapper = new QueryWrapper();
        queryWrapper.eq("table_name_code", operationRecordVo.getTableNameCode());
        queryWrapper.eq("date_purchase", operationRecordVo.getAssignmentDate());
        queryWrapper.eq("record_type", operationRecordVo.getProjectType());
        queryWrapper.eq("type_value", operationRecordVo.getDayOrNight());

        List<MesMaintenanceRecordItem> MesMaintenanceRecordItems = mesMaintenanceRecordItemMapper.selectList(queryWrapper);
        if (ObjectHelper.isNotEmpty(MesMaintenanceRecordItems)) {//存在记录
            List<String> ids = Lists.newArrayList();
            for (MesMaintenanceRecordItem item : MesMaintenanceRecordItems) {
                ids.add(item.getId());
            }
            mesMaintenanceRecordItemMapper.deleteBatchIds(ids);//执行删除
        }

        for (MaintenanceRecordProjectVo vo : operationRecordVo.getProjectVoList()) {
            MesMaintenanceRecordItem mesMaintenanceRecordItem = new MesMaintenanceRecordItem();
            mesMaintenanceRecordItemService.setMesMaintenanceRecordItem(mesMaintenanceRecordItem, mesMaintenanceRecordMain);
            mesMaintenanceRecordItem.setRecordType(operationRecordVo.getProjectType());
            mesMaintenanceRecordItem.setTypeValue(operationRecordVo.getDayOrNight());//类型值
            mesMaintenanceRecordItem.setInspectionItems(vo.getInspectionItems());//检查项目
            mesMaintenanceRecordItem.setAccountingMethod(vo.getZoneOrTime());//Zone
            mesMaintenanceRecordItem.setMeasureStandard(vo.getMeasureStandard());//衡量标准
            mesMaintenanceRecordItem.setInspectionResults(vo.getInspectionResults());//检查结果
            mesMaintenanceRecordItem.setMaintainer(operationRecordVo.getOperator());//作业员
            mesMaintenanceRecordItem.setReviewer(operationRecordVo.getReviewer());//生产主管
            if ("reflow_operation_record".equals(operationRecordVo.getTableNameCode())) {//回焊炉作业记录表
                mesMaintenanceRecordItem.setInspectionMethod(operationRecordVo.getUnusualPhenomenon());//异常现象
                mesMaintenanceRecordItem.setInspectionCycle(operationRecordVo.getImproveStrategy());//改善对策
                mesMaintenanceRecordItem.setBeCareful(operationRecordVo.getMaintainer());
            }
            mesMaintenanceRecordItemMapper.insert(mesMaintenanceRecordItem);
        }

        return Result.ok("添加成功！");
    }

    /**
     * 创建主表信息
     *
     * @param operationRecordVo
     * @return
     */
    private MesMaintenanceRecordMain addMaintenanceRecordMain(OperationRecordVo operationRecordVo) throws ParseException {
        MesChiefdataDevicearchive mesChiefdataDevicearchive = systemClient.queryByDeviceSn(operationRecordVo.getEquipmentSn());
        if (ObjectHelper.isEmpty(mesChiefdataDevicearchive)) {
            return null;
        }
        MesMaintenanceRecordMain mesMaintenanceRecordMain = new MesMaintenanceRecordMain();
        mesMaintenanceRecordMain.setId(null);
        mesMaintenanceRecordMain.setDatePurchase(new SimpleDateFormat("yyyy-MM-dd").parse(operationRecordVo.getAssignmentDate()));//作业日期
        mesMaintenanceRecordMain.setTableNameCode(operationRecordVo.getTableNameCode());//表名称编码
        mesMaintenanceRecordMain.setMaintainer(operationRecordVo.getOperator());//作业员
        mesMaintenanceRecordMain.setReviewer(operationRecordVo.getReviewer());//生产主管
        mesMaintenanceRecordMain.setEquipmentSn(operationRecordVo.getEquipmentSn());//设备SN
        if ("printing_operation_record".equals(operationRecordVo.getTableNameCode())) {//印刷机作业记录表
            mesMaintenanceRecordMain.setDocumentNumber(ObjectHelper.isNotEmpty(operationRecordVo.getFileNumber()) ? operationRecordVo.getFileNumber() : "YZY-QRQC-101");//文件编号/资产编码
            mesMaintenanceRecordMain.setBeCareful("1.每半小时确认锡膏量是否在刮刀的1/2~1/3之间,及時添加锡膏. 2.钢板手动清洗频率:每班1次/2H. 3.钢板上线使用前必须确认钢板,Support,刮刀是否清洁干净. 4.钢板张力于每次在清洗钢板之后测量并将测量数据记录于表单內. 5.若有异常,立即通知当线技术员或组长.");//注意事项
        }
        if ("reflow_operation_record".equals(operationRecordVo.getTableNameCode())) {//回焊炉作业记录表
            mesMaintenanceRecordMain.setQuery1(operationRecordVo.getMaintainer());//工程师
            mesMaintenanceRecordMain.setDocumentNumber(ObjectHelper.isNotEmpty(operationRecordVo.getFileNumber()) ? operationRecordVo.getFileNumber() : "YZY-QRQC-099");//文件编号/资产编码
        }
        mesMaintenanceRecordMain.setQuery2("版本 : 1    保密等级：一般   使用形式：纸质档   保存期限 :2年     销毁方式：双面使用");//表类型编码
        mesMaintenanceRecordMain.setTableTypeCode("operation_record");//表类型编码

        mesMaintenanceRecordMain.setLineType(mesChiefdataDevicearchive.getQuery2());//线别
        mesMaintenanceRecordMain.setEquipmentName(mesChiefdataDevicearchive.getDeviceName());//设备名称/检查项目
        mesMaintenanceRecordMain.setEquipmentModel(mesChiefdataDevicearchive.getDeviceModel());//设备型号/检查位置
        mesMaintenanceRecordMainMapper.insert(mesMaintenanceRecordMain);
        return mesMaintenanceRecordMain;
    }

    /**
     * 检查是否存在主表信息
     *
     * @param tableNameCode
     * @param assignmentDate
     * @return
     */
    private MesMaintenanceRecordMain checkMaintenanceRecordMain(String tableNameCode, String assignmentDate) {
        QueryWrapper<MesMaintenanceRecordMain> queryWrapperMain = new QueryWrapper<>();
        queryWrapperMain.eq("table_name_code", tableNameCode);
        queryWrapperMain.eq("date_purchase", assignmentDate);
        List<MesMaintenanceRecordMain> MesMaintenanceRecordMains = mesMaintenanceRecordMainMapper.selectList(queryWrapperMain);
        if (ObjectHelper.isEmpty(MesMaintenanceRecordMains)) {
            return null;
        }
        return MesMaintenanceRecordMains.get(0);
    }

}
